﻿using System.Web;
using System.Web.Routing;

namespace Basmus.Web
{
    internal class RouteCollectionWrapper
    {
        public bool IsCurrent { get; private set; }

        public string AppVirtualPath { get; private set; }

        public RouteCollection RouteCollection { get; private set; }

        public bool RouteExistingFiles
        {
            get { return RouteCollection.RouteExistingFiles; }
            set { RouteCollection.RouteExistingFiles = value; }
        }

        public RouteCollectionWrapper()
            : this(null, false)
        {

        }

        public RouteCollectionWrapper(string appVirtualPath, bool routeExistingFiles)
        {
            IsCurrent = IsCurrentApplication(appVirtualPath);
            AppVirtualPath = GetAppVirtualPath(appVirtualPath);
            RouteCollection = IsCurrent ? RouteTable.Routes : new RouteCollection();
            RouteCollection.RouteExistingFiles = routeExistingFiles;
        }

        public VirtualPathData GetVirtualPath(string name, RouteValueDictionary values)
        {
            var requestContext = IsCurrent ? null : FakeRequestContext;
            var route = RouteCollection[name];
            if (route == null)
            {
                return null;
            }
            var virtualPathData = RouteCollection.GetVirtualPath(requestContext, name, values);
            return virtualPathData;
        }

        public VirtualPathData GetVirtualPath(RouteValueDictionary values)
        {
            var requestContext = IsCurrent ? null : FakeRequestContext;
            var virtualPathData = RouteCollection.GetVirtualPath(requestContext, values);
            return virtualPathData;
        }

        private RequestContext _requestContext;

        protected RequestContext FakeRequestContext
        {
            get
            {
                if (_requestContext == null)
                {
                    var fakeHttpContext = new FakeHttpContext(AppVirtualPath);
                    _requestContext = new RequestContext(fakeHttpContext, new RouteData());
                }
                return _requestContext;
            }
        }

        public static string GetAppVirtualPath(string appVirtualPath = null)
        {
            return IsCurrentApplication(appVirtualPath) ? HttpRuntime.AppDomainAppVirtualPath : appVirtualPath;
        }

        public static bool IsCurrentApplication(string appVirtualPath = null)
        {
            return appVirtualPath == null ||
                   (HttpRuntime.AppDomainAppVirtualPath != null &&
                    HttpRuntime.AppDomainAppVirtualPath.ToLower() ==
                    appVirtualPath.ToLower());
        }
    }
}
